package com.qingyun.shop.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.qingyun.common.config.QingYunConfig;
import com.qingyun.common.config.VideoConfig;
import com.qingyun.common.constant.Constants;
import com.qingyun.common.exception.CustomException;
import com.qingyun.common.exception.ServiceException;
import com.qingyun.common.utils.PageUtils;
import com.qingyun.common.core.page.PagePlus;
import com.qingyun.common.core.page.TableDataInfo;
import com.qingyun.common.utils.file.MimeTypeUtils;
import com.qingyun.video.domain.TiktokVideoMerge;
import com.qingyun.video.ffmpeg.MultimediaInfo;
import com.qingyun.video.ffmpeg.VideoSize;
import com.qingyun.video.utils.Mp4Utils;
import com.qingyun.security.utils.SecurityUtils;
import com.qingyun.shop.domain.TiktokResource;
import com.qingyun.shop.domain.TiktokResourceGroup;
import com.qingyun.shop.domain.TiktokShop;
import com.qingyun.shop.domain.bo.resource.TiktokResourceAddBo;
import com.qingyun.shop.domain.bo.resource.TiktokResourceEditBo;
import com.qingyun.shop.domain.bo.resource.TiktokResourceQueryBo;
import com.qingyun.shop.domain.vo.TiktokResourceVo;
import com.qingyun.shop.mapper.TiktokResourceGroupMapper;
import com.qingyun.shop.mapper.TiktokResourceMapper;
import com.qingyun.shop.service.ITiktokResourceService;
import com.qingyun.shop.service.ITiktokShopService;
import com.qingyun.video.utils.VideoUtil;
import lombok.AllArgsConstructor;
import ma.glasnost.orika.MapperFacade;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import com.qingyun.common.core.mybatisplus.core.ServicePlusImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.transaction.annotation.Transactional;


import java.io.File;
import java.util.List;
import java.util.Collection;
import java.util.Map;

/**
 * 资源Service业务层处理
 *
 * @author qingyun
 * @date 2021-09-04
 */
@Service
@AllArgsConstructor
public class TiktokResourceServiceImpl extends ServicePlusImpl<TiktokResourceMapper, TiktokResource, TiktokResourceVo> implements ITiktokResourceService {

	private final MapperFacade mapperFacade;

	private final TiktokResourceGroupMapper resourceGroupMapper;

	private final VideoConfig videoConfig;

	private final ITiktokShopService tiktokShopService;

    @Override
    public TiktokResourceVo queryById(Long id){
        return getVoById(id);
    }

    @Override
    public TableDataInfo<TiktokResourceVo> queryPageList(TiktokResourceQueryBo bo) {
        PagePlus<TiktokResource, TiktokResourceVo> result = pageVo(PageUtils.buildPagePlus(), buildQueryWrapper(bo));
        result.getRecordsVo().forEach((resourceVo)->{
			Long groupId = resourceVo.getGroupId();
			TiktokResourceGroup tiktokResourceGroup = resourceGroupMapper.selectById(groupId);
			resourceVo.setGroupName(tiktokResourceGroup.getGroupName());
			resourceVo.setDurationStr(DateUtil.secondToTime(resourceVo.getDuration().intValue()));
		});
		return PageUtils.buildDataInfo(result);
    }

    @Override
    public List<TiktokResourceVo> queryList(TiktokResourceQueryBo bo) {
        return listVo(buildQueryWrapper(bo));
    }

    private LambdaQueryWrapper<TiktokResource> buildQueryWrapper(TiktokResourceQueryBo bo) {
    	if(!SecurityUtils.isManager()) {
			bo.setShopId(SecurityUtils.getShop().getId());
		}
        LambdaQueryWrapper<TiktokResource> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getShopId() != null, TiktokResource::getShopId, bo.getShopId());
        lqw.eq(bo.getShopName()!=null, TiktokResource::getShopName,bo.getShopName());
        lqw.eq(bo.getFormat()!=null,TiktokResource::getFormat,bo.getFormat());
        lqw.eq(bo.getIsFrag()!=null,TiktokResource::getIsFrag,bo.getIsFrag());
        lqw.eq(bo.getGroupId() != null, TiktokResource::getGroupId, bo.getGroupId());
        lqw.eq(bo.getResourceType() != null, TiktokResource::getResourceType, bo.getResourceType());
        lqw.like(StringUtils.isNotBlank(bo.getResourceName()), TiktokResource::getResourceName, bo.getResourceName());
        lqw.orderByDesc(TiktokResource::getCreateTime);
        return lqw;
    }

    @Override
	@Transactional(rollbackFor = Exception.class)
	@CacheEvict(cacheNames = "GetAcitvity", allEntries=true)
    public Boolean insertByBo(TiktokResourceAddBo bo) {
		TiktokResource resourceAdd = mapperFacade.map(bo, TiktokResource.class);

		if(!SecurityUtils.isManager()){
			resourceAdd.setShopId(SecurityUtils.getShop().getId());
		}

		if (ObjectUtil.isNull(resourceAdd.getShopId())) {
           throw new ServiceException("商户id不存在");
		}

		TiktokShop tiktokShop = tiktokShopService.getById(resourceAdd.getShopId());
		if (tiktokShop==null) {
			throw new CustomException("商户不存在");
		}

		resourceAdd.setShopName(tiktokShop.getName());
		String[] resources = resourceAdd.getResourceUrl().split(",");
		for (String resource : resources) {
			resourceAdd.setResourceUrl(resource);
			validEntityBeforeSave(resourceAdd);
			save(resourceAdd);
		}

		return true;
    }

	@Override
	public TiktokResource selectRandomResourceByGroupId(Long shopId,Long groupId,Integer format,Integer isFrag) {
		return baseMapper.selectRandomResourceByGroupId(shopId,groupId,format,isFrag);
	}

	@Override
	@CacheEvict(cacheNames = "GetAcitvity", allEntries=true)
    public Boolean updateByBo(TiktokResourceEditBo bo) {
		TiktokResource resourceEdit = mapperFacade.map(bo, TiktokResource.class);
		validEntityBeforeSave(resourceEdit);
        return updateById(resourceEdit);
    }


	/**
	 * 保存前的数据校验
	 *
	 * @param entity 实体类数据
	 */
	private void validEntityBeforeSave(TiktokResource entity) {
		String resource = entity.getResourceUrl();
		String localPath = QingYunConfig.getProfile() + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
		MultimediaInfo videoInfoByFile = null;
		try {
			videoInfoByFile = VideoUtil.getVideoInfoByFile(localPath);
		} catch (Exception e) {
			e.printStackTrace();
			File file = new File(localPath);
			file.delete();
			throw new ServiceException("视频解析错误");
		}
		VideoSize videoSize = videoInfoByFile.getVideo().getSize();
		int width = videoSize.getWidth();
		int height = videoSize.getHeight();
		int wt = width / 120;
		int he = height / 120;
			if (wt>he) {
				entity.setFormat(Constants.P1080TRANSVERSE);
			}else if(wt<he){
				entity.setFormat(Constants.P1080PORTRAIT);
			}else {
				File file = new File(localPath);
				file.delete();
				throw new ServiceException("视频比例不正确");
			}
			entity.setDuration(Double.valueOf(videoInfoByFile.getDuration()/1000));
	}

    @Override
	@CacheEvict(cacheNames = "GetAcitvity", allEntries=true)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
		for (TiktokResource resource : listByIds(ids)) {
			String localPath = QingYunConfig.getProfile() + StringUtils.substringAfter(resource.getResourceUrl(),  Constants.RESOURCE_PREFIX);
			File file = new File(localPath);
			if (file.exists()) {
				file.delete();
			}
		}
        return removeByIds(ids);
    }

	@Override
	public Boolean groupIdCheck(Long groupId) {
		return resourceGroupMapper.selectById(groupId) == null;
	}
}
